package com.basic.business.pathRel.service.impl;

import com.basic.business.common.constants.Constants;
import com.basic.business.common.redis.RedisCacheUtils;
import com.basic.business.pathRel.domain.TPathRel;
import com.basic.business.pathRel.mapper.ITPathRelMapper;
import com.basic.business.pathRel.service.ITPathRelService;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 路径关系表服务实现类
 *
 * @author zhaoxy_jn@163.com
 */
@Service
public class TPathRelServiceImpl implements ITPathRelService {

    @Resource
    private ITPathRelMapper pathRelMapper;

    /**
     * 项目启动时，初始化路劲缓存
     */
    @PostConstruct
    public void init(){
        resetPathRelCache();
    }

    @Override
    public List<TPathRel> getNormalMatPathRel() {
        return pathRelMapper.getNormalMatPathRel();
    }

    /**
     * 重置路径关系缓存
     */
    private void resetPathRelCache() {
        // 清空缓存
        RedisCacheUtils.clearCache(Constants.PATH_REL_REDIS_KEY + "*");
        // 加载缓存
        loadingPathRelCache();
    }

    /**
     * 加载路径关系缓存
     */
    private void loadingPathRelCache() {

        Map<String, TPathRel> pathRelMap = getNormalMatPathRel().stream().collect(Collectors.toMap(TPathRel::getPathName, pathRel -> pathRel));
        for (Map.Entry<String, TPathRel> entry : pathRelMap.entrySet()) {
            RedisCacheUtils.setCacheObject(Constants.PATH_REL_REDIS_KEY + entry.getKey(), entry.getValue());
        }

    }
}
